<template>
  <div>
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
      @changeAddress="changeAddressMap"
    ></VForm>

    <div class="formTitle-root" v-if="openType=='dispose' || (openType=='detail' && curDisposeStatus==2)">
      <div class="form-title-p">处置信息</div>
    </div>
    <VForm
      v-if="openType=='dispose' || (openType=='detail' && curDisposeStatus==2)"
      ref="vformComponents1"
      :form="formData1.form"
      :options="formData1.options"
      :rules="formData1.rules"
      :labelWidth="formData1.labelWidth"
      :rowspan="rowspan"
    ></VForm>

    <div class="e-dialog-footer">
      <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
      </span>
    </div>
  </div>
</template>

<script>
  import {
    alarmWarningDetail,
    alarmWarningUpdate,
    alarmWarningAdd
  } from '@/api/alarm/warning'
  import VForm from "@/components/VForm";
  import {alarmRecordList} from "@/api/alarm/record";

  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "70%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id: {},
      openType: {
        type: String,
        default: "add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      curDisposeStatus:{}
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          console.log('newVal===', newVal, oldVal)
          let w = this.width.split('%')[0]
          if (w >= 60) {
            this.rowspan = 2
          } else {
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'modeType': {
        handler(newVal, oldVal) {
          this.formData.form.modeType = newVal;
        },
        deep: true,
        immediate: true
      },
      'warnType': {
        handler(newVal, oldVal) {
          this.formData.form.warnType = newVal;
        },
        deep: true,
        immediate: true
      },
      'warnTypeOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'warnType') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'warnLevelOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'warnLevel') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'statusOptions': {
        handler(newVal, oldVal) {
          this.formData.options.forEach(t => {
            if (t.key == 'status') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'disposeStatusOptions': {
        handler(newVal, oldVal) {
          this.formData1.options.forEach(t => {
            if (t.key == 'disposeStatus') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'contactAlarmIdOptions': {
        handler(newVal, oldVal) {
          this.formData1.options.forEach(t => {
            if (t.key == 'contactAlarmId') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      dialogVisible:{
        handler(newVal, oldVal) {
          if(newVal){
            console.log("监测指===",newVal)
            this.getData()
          }
        },
        deep: true,
        immediate: true
      },
      openType:{
        handler(newVal, oldVal) {
          this.formData.options = this.formData.options.filter(t=> !t.readonly)
          if(newVal != 'add'){
            let item = {
              title: "标识码",
              key: "identificationCode",
              type: "text",
              disabled: true,
              readonly:true
            }
            this.formData.options.unshift(item)
          }
          this.formData.options.forEach(t => {
            if(!t.readonly) {
              t.disabled = newVal == 'detail' || newVal == 'dispose' ? true : false
            }
          })
          this.formData1.options.forEach(t => {
            t.disabled = newVal == 'detail' ? true : false
          })
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        modeType: '',

        rowspan: 1,
        dict: {},
        formData: {
          form: {
            modeType: this.modeType,
            identificationCode: "",
            cityDescription: "",
            address: "",
            warnCode: "",
            warnName: "",
            project: "",
            warnType: "2",
            warnLevel: "",
            status: "",
            warnTime: "",
            warnReportTime: "",
            warnContent: "",
            warnReportContent: [],
            pic: "",
            research: "",
            analyseFile: [],
            lon: "",
            lat: "",
            provinceCode: "",
            cityCode: "",
            countyCode: "",
            areaCode: "",
            createUser: "",
            updateTime: "",
            updateUser: "",
            mapData:null,
          },
          options: [
            // {
            //   title: "标识码",
            //   key: "identificationCode",
            //   type: "text",
            // },
            {
              title: "预警编号",
              key: "warnCode",
              type: "text",
            },
            {
              title: "预警名称",
              key: "warnName",
              type: "text",
            },
            {
              title: "城市简述",
              key: "cityDescription",
              type: "textarea",
              columnWidth:'w100',
            },
            {
              title: "详细地址",
              // key: "address",
              // type: "text",
              type:'mapPosition',
              key:'mapData',
            },
            {
              title: "所属专项",
              key: "project",
              type: "text",
            },
            {
              title: "预警类型",
              key: "warnType",
              type: "select",
              multiple: false,
              disabled: true,
              option: {
                data: this.warnTypeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "预警级别",
              key: "warnLevel",
              type: "select",
              multiple: false,
              option: {
                data: this.warnLevelOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "预警状态",
              key: "status",
              type: "select",
              option: {
                data: this.statusOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "预警时间",
              key: "warnTime",
              type: "datetime",
            },
            {
              title: "预警上报时间",
              key: "warnReportTime",
              type: "datetime",
            },
            {
              title: "预警内容",
              key: "warnContent",
              type: "text",
            },
            {
              title: "预警报告",
              key: "warnReportContent",
              type: "file",
              fileType: "file",
              listType: "text",
              uploadTextTip: ""
            },
            {
              title: "研判分析",
              key: "research",
              type: "textarea",
              columnWidth:'w100',
            },
            {
              title: "分析报告",
              key: "analyseFile",
              type: "file",
              fileType: "file",
              listType: "text",
              uploadTextTip: ""
            },
          ],
          rules: {
            // identificationCode: [
            //   {required: true, message: '请输入', trigger: 'blur'},
            //   {max: 20, message: '长度最大为20个字符', trigger: 'blur'}
            // ],
            cityDescription: [
              {max: 500, message: '长度最大为500个字符', trigger: 'blur'}
            ],
            address: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 150, message: '长度最大为150个字符', trigger: 'blur'}
            ],
            warnCode: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 100, message: '长度最大为100个字符', trigger: 'blur'}
            ],
            warnName: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 120, message: '长度最大为120个字符', trigger: 'blur'}
            ],
            project: [
              {max: 100, message: '长度最大为100个字符', trigger: 'blur'}
            ],
            warnLevel: [{required: true, message: '请输入', trigger: 'change'},],
            status: [{required: true, message: '请输入', trigger: 'change'},],
            warnTime: [{required: true, message: '请输入', trigger: 'change'},],
            warnReportTime: [{required: true, message: '请输入', trigger: 'change'},],
            warnContent: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
            warnReportContent: [],
            pic: [
              {max: 1024, message: '长度最大为1024个字符', trigger: 'blur'}
            ],
            research: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 1024, message: '长度最大为1024个字符', trigger: 'blur'}
            ],
            analyseFile: [{required: true, message: '请输入', trigger: 'change'},],
          },
          labelWidth: "160px",
        },
        formData1: {
          form: {
            disposeStatus: "",
            disposeUser: "",
            disposeTime: "",
            disposeAdvice: "",
            disposeFile: [],
            disposePic: "",
            contactAlarm: "",
            contactAlarmId: "",
          },
          options: [
            {
              title: "处置状态",
              key: "disposeStatus",
              type: "select",
              option: {
                data: this.disposeStatusOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "处置人",
              key: "disposeUser",
              type: "text",
            },
            {
              title: "处置时间",
              key: "disposeTime",
              type: "datetime",
            },
            {
              title: "处置建议",
              key: "disposeAdvice",
              type: "text",
            },
            {
              title: "关联报警记录",
              key: "contactAlarmId",
              type: "select",
              disabled: false,
              event: 'changeAlarmName',
              option: {
                data: this.contactAlarmIdOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "alarmName", // 指定label对应data的字段
                  value: "id", // 指定value对应data的字段
                },
              },
            },
            {
              title: "处置报告",
              key: "disposeFile",
              type: "file",
              fileType: "file",
              listType: "text",
              uploadTextTip: ""
            },
          ],
          rules: {
            disposeStatus: [{required: true, message: '请输入', trigger: 'change'},],
            disposeUser: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 20, message: '长度最大为20个字符', trigger: 'blur'}
            ],
            disposeTime: [
              {required: true, message: '请输入', trigger: 'blur'},
            ],
            disposeAdvice: [
              {required: true, message: '请输入', trigger: 'blur'},
              {max: 256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
            disposeFile: [{required: true, message: '请输入', trigger: 'blur'},],
            disposePic: [
              {max: 1024, message: '长度最大为1024个字符', trigger: 'blur'}
            ],
          },
          labelWidth: "160px",
        },
        // 字典
        warnTypeOptions: [],
        warnLevelOptions: [],
        statusOptions: [],
        disposeStatusOptions: [],
        contactAlarmIdOptions: [],
      };
    },
    methods: {
      changeAddressMap(data){
        console.log("changeAddressMap=====>",data)
        this.formData.form.mapData = data
        this.formData.form.areaCode = data.areaCode
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      changeAlarmName() {
        const contactAlarmId = this.formData.form.contactAlarmId
        let item = this.contactAlarmIdOptions.find(t => t.id == contactAlarmId)
        if (item) {
          this.formData.form.contactAlarm = item.alarmName
          // this.changeAddress(item)
        }
      },
      changeAddress(data) {
        console.log('changeAddress', data)
        this.formData.form.lon = data.lon
        this.formData.form.lat = data.lat
        this.formData.form.address = data.alarmAddress

        this.formData.form.provinceCode = data.provinceCode
        this.formData.form.cityCode = data.cityCode
        this.formData.form.countyCode = data.countyCode
        this.formData.form.areaCode = data.areaCode
      },
      submitFormat() {
        this.formData.form.analyseFile = JSON.stringify(this.formData.form.analyseFile)
        this.formData1.form.disposeFile = JSON.stringify(this.formData1.form.disposeFile)
        this.formData.form.warnReportContent = JSON.stringify(this.formData.form.warnReportContent)
      },
      loadFormat() {
        this.formData.form.analyseFile = this.formData.form.analyseFile ? JSON.parse(this.formData.form.analyseFile) : []
        this.formData1.form.disposeFile = this.formData1.form.disposeFile ? JSON.parse(this.formData1.form.disposeFile) : []
        this.formData.form.warnReportContent = this.formData.form.warnReportContent ? JSON.parse(this.formData.form.warnReportContent) : []
      },
      positionSubmitFormat() {
        let mapData = this.formData.form.mapData
        if(mapData){
          this.formData.form.lon = mapData.gpsX
          this.formData.form.lat = mapData.gpsY
          this.formData.form.address = mapData.address
          this.formData.form.areaCode = mapData.towncode
          if(mapData.towncode){
            this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
            this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
            let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
            this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
          }
          if(Array.isArray(this.formData.form.areaCode) &&  this.formData.form.areaCode[0] == ''){
            console.log("赋值空", this.formData.form.areaCode)
            this.formData.form.areaCode = null
          }
        }
      },
      getCountySubIndex(cityCode){
        // 中山、东莞截取10位
        let filterList = ['442000000000','441900000000']
        if(filterList.findIndex(t=>t==cityCode)>-1){
          return 10;
        }
        return 6;
      },
      positionLoadFormat(){
        let form = this.formData.form
        let mapData = {}
        mapData.address = form.address
        mapData.gpsX = parseFloat(form.lon)
        mapData.gpsY = parseFloat(form.lat)
        mapData.towncode = form.areaCode
        this.formData.form.mapData = mapData
        console.log("mpap",mapData)
      },
      getCheckBoxData(value, option, type) {
        if (type == "submit") {
          if (value.length == 0) {
            return null
          }
          let temp = [];
          value.forEach(t => {
            let item = option.find(x => x.label == t)
            if (item != undefined) {
              temp.push(item.value)
            }
          })
          return temp.join(",")
        } else {
          if (!value) {
            return []
          } else {
            let data = value.split(",")
            let temp = []
            data.forEach(t => {
              let item = option.find(x => x.value == t)
              if (item != undefined) {
                temp.push(item.label)
              }
            })
            return temp
          }
        }
      },
      sure() {
        // this.formData.form.identificationCode="1"
        console.log('sure===', this.formData.form)
        if(this.openType=='dispose'){
          this.$refs.vformComponents1.$refs.form.validate().then(res => {
            this.submitFormat()
            this.positionSubmitFormat()
            this.dispose()
          })
        }else {
          this.$refs.vformComponents.$refs.form.validate().then(res => {
            this.submitFormat()
            this.positionSubmitFormat()
            delete this.formData.form.disposeStatus
            delete this.formData.form.disposeUser
            delete this.formData.form.disposeTime
            delete this.formData.form.disposeAdvice
            delete this.formData.form.disposeFile
            delete this.formData.form.disposePic
            delete this.formData.form.contactAlarm
            delete this.formData.form.contactAlarmId
            delete this.formData.form.disposeUnit
            if (this.openType == "add") {
              this.add()
            } else {
              this.update()
            }
          })
        }
      },
      dispose(){
        alarmWarningUpdate({id:this.id,...this.formData1.form}).then(res=>{
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      add() {
        this.formData.form.id = null
        this.formData.form.warnType = '2'
        alarmWarningAdd(this.formData.form).then(res => {
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      update() {
        alarmWarningUpdate(this.formData.form).then(res => {
          if (res.code == 200) {
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      cancel() {
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess() {
        this.$refs.vformComponents.$refs.form.resetFields();
        if(this.$refs.vformComponents1){
          this.$refs.vformComponents1.$refs.form.resetFields();
        }
        this.$emit('success')
      },
      close(val) {
        this.$refs.vformComponents.$refs.form.resetFields();
        if(this.$refs.vformComponents1){
          this.$refs.vformComponents1.$refs.form.resetFields();
        }
        if(!val){
          this.$emit('close')
        }
      },
      getData() {
        if (this.openType != "add") {
          alarmWarningDetail(this.id).then(res => {
            if (res.code == 200) {
              res.data.warnType=parseInt(res.data.warnType)
              res.data.status=parseInt(res.data.status)
              this.formData.form = res.data
              this.formData1.form = res.data
              this.getAlarmList(res.data.contactAlarmId,'')
              this.changeDisabled(true)
              this.loadFormat()
              this.positionLoadFormat()
            } else {
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        } else {
          //add
          this.getAlarmList('','2')
          this.changeDisabled(false)
        }
      },
      changeDisabled(value) {
        // this.formData1.options.find(t => t.key == 'contactAlarmId').disabled = value;
      },
      getAlarmList(id,alarmType) {
        alarmRecordList({"id": id,"modeType":this.modeType,"alarmType":alarmType}).then(res => {
          if (res.code == 200) {
            this.contactAlarmIdOptions = res.data
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      },
      initAlarmConfig() {
        let type = this.$route.path
        console.log("path:" + type)
        const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
        this.modeType = config.modeTypeYj
      }
    },
    created() {
      this.initAlarmConfig()
      let warnType = this.$commonJs.getAlarmPathConfig(this.$route.path).warnType
      this.warnTypeOptions = []
      this.$commonJs.filterDataDict(warnType, this.warnTypeOptions)
      this.formData.form.warnType = 2
      this.warnLevelOptions = []
      this.$commonJs.filterDataDict("waringLevel", this.warnLevelOptions)
      this.statusOptions = []
      this.$commonJs.filterDataDict("waringStatus", this.statusOptions)
      this.disposeStatusOptions = []
      this.$commonJs.filterDataDict("disposeStatus", this.disposeStatusOptions)
      //报警记录
      this.getAlarmList('','2')
    }
  };
</script>

<style lang="scss" scoped>
  .e-dialog-footer{
    padding: 20rem 0 4rem 20rem;
    text-align: right;
    box-sizing: border-box;
  }
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 5px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
</style>
